/* © 2007 Adobe Systems Incorporated. All rights reserved. */
package com.shubhjai.musiclib.util
{
	import com.shubhjai.musiclib.model.Record;
	import com.shubhjai.musiclib.commands.GetRecordImageCommand;
	import com.shubhjai.musiclib.events.CommandCompleteEvent;
	import flash.events.EventDispatcher;
	import flash.display.Bitmap;
	import flash.events.ErrorEvent;
	import flash.events.Event;
	
	/**
	 * This class serves as an easily bindable source for the asynchronous loading
	 * of bitmap data, employing a fallback bitmap to show in case an image is 
	 * unavailable.
	 */ 
	public class RecordImageProxy extends EventDispatcher
	{
		
		private var _employee : Record;
		private var _imageBitmap : Bitmap;
		
		[Embed('/embed_assets/image_unavailable.png')]
		private static var imageUnavailClass : Class;
		
		/**
		 * Constructor
		 */ 
		public function RecordImageProxy() : void
		{
			
		}
		
		[Bindable]
		/**
		 * Get the empplo
		 */ 
		public function get employee() : Record
		{
			return _employee;
		}
		
		/**
		 * Set the employee. This will update the imageData automatically.
		 */ 
		public function set employee( emp:Record ) : void
		{
			_employee = emp;
			
			_imageBitmap = null;
			dispatchEvent( new Event( "imageDataUpdated" ) );
			
			if ( emp != null )
			{
			
				var cmd : GetRecordImageCommand = new GetRecordImageCommand( emp );	
				cmd.addEventListener( CommandCompleteEvent.COMPLETE, onImageLoad );
				cmd.addEventListener( ErrorEvent.ERROR, onImageLoadError );
				cmd.execute();
			}
		}
		
		private function onImageLoad( evt:CommandCompleteEvent ) : void
		{
			var cmd : GetRecordImageCommand = evt.target as GetRecordImageCommand;
			cmd.removeEventListener( CommandCompleteEvent.COMPLETE, onImageLoad );
			cmd.removeEventListener( ErrorEvent.ERROR, onImageLoadError );
			
			_imageBitmap = cmd.imageBitmap;
			dispatchEvent( new Event( "imageDataUpdated" ) );
		}
		
		private function onImageLoadError( evt:Event ) : void
		{
			var cmd : GetRecordImageCommand = evt.target as GetRecordImageCommand;
			cmd.removeEventListener( CommandCompleteEvent.COMPLETE, onImageLoad );
			cmd.removeEventListener( ErrorEvent.ERROR, onImageLoadError );
			
			_imageBitmap = null;
			dispatchEvent( new Event( "imageDataUpdated" ) );
		}
		
		[Bindable("imageDataUpdated")]
		public function get imageBitmap() : Bitmap
		{
			if ( _imageBitmap != null )
			{
				return _imageBitmap;
			}
			else
			{
				return new imageUnavailClass();
			}
		}

	}
}